package com.server.core.domain;

/**
 * @desc 前缀树存储路由信息
 */

import java.lang.reflect.Method;

public class Trie {
    public Trie() {

    }
    static class TrieNode {
        TrieNode[] map;
        Method method;
        TrieNode(Class clazz) {
            map = new TrieNode[200];
        }
    }

    private static  TrieNode trieNode = new TrieNode(null);
    public void  insert(String word, Method method) {
        char[] cs = word.toCharArray();
        TrieNode node = trieNode;
        for(int i = 0; i < cs.length; i++) {
              try{
                  if( node.map[cs[i]] == null) {
                      node.map[cs[i]] = new TrieNode(null);
                  }
                  node = node.map[cs[i]];
                  if(i == cs.length - 1) {
                      node.method = method;
                  }
              }catch (IndexOutOfBoundsException e) {
                  System.err.println("字符插入范围溢出");
                  e.printStackTrace();
              }
         }
    }


    public Method get(String word) {

        if(word==null || word.length() == 0) {
            return null;
        }
        if(word.equals("/")) {
            return  trieNode.map['/'].method;
        }
        Method method = null;
        char[] cs = word.toCharArray();
        TrieNode node = trieNode;
        for(int i = 0; i < cs.length; i++) {
            if( node.map[cs[i]] == null) {
                 break;
            }
            node = node.map[cs[i]];
            if(node.method != null && ( i == cs.length - 1 || cs[i+1] == '/')) {
                method = node.method;
            }
        }
        return method;
    }
}
